package org.flowers.unbeaten.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.flowers.unbeaten.base.entity.UserRole;
import org.flowers.unbeaten.mapper.UserRoleMapper;
import org.flowers.unbeaten.service.IUserRoleService;
import org.flowers.unbeaten.base.vo.UserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author RyanWang
 * @since 2021-07-15
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List getRoleIdsByUserId(String userId) {
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.<UserRole>lambdaQuery().select(UserRole::getRoleId).eq(UserRole::getUserId, userId);
        return userRoleMapper.selectObjs(wrapper);
    }

    @Override
    public List getUserIdsByRoleId(String roleId) {
        return userRoleMapper.selectObjs(Wrappers.<UserRole>lambdaQuery().select(UserRole::getUserId).eq(UserRole::getRoleId, roleId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(UserRoleVo vo) {
        if (CollectionUtils.isEmpty(vo.getRoleIds())) {
            return;
        }
        List<UserRole> userRoles = new ArrayList<>();
        for (String roleId : vo.getRoleIds()) {
            UserRole userRole = new UserRole();
            userRole.setUserId(vo.getUserId());
            userRole.setRoleId(roleId);
            userRoles.add(userRole);
        }
        userRoleMapper.delete(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, vo.getUserId()));
        // 批量插入
        this.saveBatch(userRoles);
    }
}
